<?php
namespace app\controller;

use app\BaseController;
use app\model\OperationLog as OperationLogModel;
use think\facade\Db;

class Log extends BaseController
{
    /**
     * 获取操作日志列表
     */
    public function operationList()
    {
        // 获取请求参数
        $params = $this->request->get();
        
        // 构建查询
        $query = OperationLogModel::order('id', 'desc');
        
        // 按操作内容搜索
        if (!empty($params['operation'])) {
            $query = $query->searchOperationAttr($params['operation']);
        }
        
        // 按用户名搜索
        if (!empty($params['username'])) {
            $query = $query->searchUsernameAttr($params['username']);
        }
        
        // 按IP搜索
        if (!empty($params['ip'])) {
            $query = $query->searchIpAttr($params['ip']);
        }
        
        // 按模块搜索
        if (!empty($params['module'])) {
            $query = $query->searchModuleAttr($params['module']);
        }
        
        // 按业务类型搜索
        if (isset($params['business_type']) && $params['business_type'] !== '') {
            $query = $query->searchBusinessTypeAttr($params['business_type']);
        }
        
        // 按状态搜索
        if (isset($params['status']) && $params['status'] !== '') {
            $query = $query->searchStatusAttr($params['status']);
        }
        
        // 按时间范围搜索
        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $query = $query->searchTimeRangeAttr([$params['start_time'], $params['end_time']]);
        }
        
        // 分页
        $list = $query->paginate([
            'list_rows' => $params['pageSize'] ?? 10,
            'page' => $params['page'] ?? 1,
        ]);
        
        return $this->success('获取成功', $list);
    }
    
    /**
     * 获取操作日志详情
     * @param int $id 日志ID
     */
    public function operationDetail($id)
    {
        // 验证参数
        if (!$id || !is_numeric($id)) {
            return $this->error('参数错误');
        }
        
        // 查询日志
        $log = OperationLogModel::find($id);
        if (!$log) {
            return $this->error('日志不存在');
        }
        
        return $this->success('获取成功', $log);
    }
    
    /**
     * 删除操作日志
     * @param int $id 日志ID
     */
    public function deleteOperation($id)
    {
        // 验证参数
        if (!$id || !is_numeric($id)) {
            return $this->error('参数错误');
        }
        
        // 查询日志
        $log = OperationLogModel::find($id);
        if (!$log) {
            return $this->error('日志不存在');
        }
        
        // 删除日志
        if ($log->delete()) {
            return $this->success('删除成功');
        } else {
            return $this->error('删除失败');
        }
    }
    
    /**
     * 清空操作日志
     */
    public function clearOperation()
    {
        // 清空日志
        Db::execute('TRUNCATE TABLE ' . OperationLogModel::getTable());
        
        return $this->success('清空成功');
    }
    
    /**
     * 获取操作日志统计信息
     */
    public function operationStats()
    {
        // 获取今日日志数量
        $today = date('Y-m-d');
        $todayLogs = OperationLogModel::whereDay('operate_time', $today)->count();
        
        // 获取总日志数量
        $totalLogs = OperationLogModel::count();
        
        // 获取操作成功数量
        $successLogs = OperationLogModel::where('status', 1)->count();
        
        // 获取操作失败数量
        $failLogs = OperationLogModel::where('status', 0)->count();
        
        // 获取最近的操作日志
        $recentLogs = OperationLogModel::order('id', 'desc')
            ->limit(5)
            ->select();
        
        return $this->success('获取成功', [
            'today_logs' => $todayLogs,
            'total_logs' => $totalLogs,
            'success_logs' => $successLogs,
            'fail_logs' => $failLogs,
            'recent_logs' => $recentLogs
        ]);
    }
    
    /**
     * 记录操作日志
     * @param array $data 日志数据
     * @return bool 是否成功
     */
    public static function record($data)
    {
        try {
            OperationLogModel::create($data);
            return true;
        } catch (\Exception $e) {
            // 记录失败，写入错误日志
            \think\facade\Log::error('记录操作日志失败：' . $e->getMessage());
            return false;
        }
    }
} 